package com.wolfsea.definerectdemo
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Rect
import android.util.AttributeSet
import android.util.Log
import android.view.View
import kotlinx.coroutines.*

/**
 *@desc  JumpRectView
 *@author liuliheng
 *@time 2022/12/1  20:48
 **/
class JumpRectView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null) :
    View(context, attributeSet),CoroutineScope by MainScope() {

    private var mWidth = 0
    private var mHeight = 0

    private var mPerRectWidth = 0

    private var job: Job? = null

    private val rectPaint by lazy {
        Paint().apply {
            isAntiAlias = true
            isDither = true
            color = context.resources.getColor(R.color.purple_200)
        }
    }

    private val random by lazy {
        java.util.Random()
    }

    private val rect by lazy {
        Rect()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        mWidth = when (MeasureSpec.getMode(widthMeasureSpec)) {
            MeasureSpec.EXACTLY -> {
                Math.max(
                    MeasureSpec.getSize(widthMeasureSpec),
                    context.resources.getDimension(R.dimen.dp_48).toInt()
                )
            }
            else -> {
                context.resources.getDimension(R.dimen.dp_80).toInt()
            }
        }

        mHeight = when (MeasureSpec.getMode(heightMeasureSpec)) {
            MeasureSpec.EXACTLY -> {
                Math.max(
                    MeasureSpec.getSize(heightMeasureSpec),
                    context.resources.getDimension(R.dimen.dp_40).toInt()
                )
            }
            else -> {
                context.resources.getDimension(R.dimen.dp_60).toInt()
            }
        }

        setMeasuredDimension(mWidth, mHeight)

        mPerRectWidth = mWidth / PIECES
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        for (i in 0.until(PIECES)) {
            if (i % 2 == 0) {
                rect.set(i * mPerRectWidth,
                    random.nextInt(mHeight),
                    (i + 1) * mPerRectWidth,
                    mHeight)
                canvas?.drawRect(rect, rectPaint)
            }
        }
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        job = launch(Dispatchers.IO) {
            while (true) {
                delay(300)
                invalidate()
            }
        }
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        job?.cancel()
        Log.d(TAG, "onDetachedFromWindow")
    }

    companion object {
        const val TAG = "JumpRectView"
        const val PIECES = 8
    }
}